import csv
import numpy

data1 = csv.DictReader(open('avg_0.csv'))
data2 = csv.DictReader(open('avg_1.csv'))
data3 = csv.DictReader(open('avg_2.csv'))
data4 = csv.DictReader(open('avg_3.csv'))
data5 = csv.DictReader(open('avg_4.csv'))
data6 = csv.DictReader(open('avg_5.csv'))
data7 = csv.DictReader(open('avg_6.csv'))
data8 = csv.DictReader(open('avg_7.csv'))
data9 = csv.DictReader(open('avg_8.csv'))
data10 = csv.DictReader(open('avg_9.csv'))

data_list = [data1, data2, data3, data4, data5, data6, data7, data8, data9, data10]

tax_data = {}

taxes = range(250)

for tax in taxes:
    tax_data[tax/10.] = {}

for data in data_list:
    for sugarscape in data:
        for key, val in sugarscape.iteritems():
            try:
                tax_data[float(sugarscape['tax_rate'])][key].append(float(val))
            except KeyError:
                tax_data[float(sugarscape['tax_rate'])][key] = [float(val)]
            if len(tax_data[float(sugarscape['tax_rate'])][key]) == 10:
                tax_data[float(sugarscape['tax_rate'])][key] = numpy.average(tax_data[float(sugarscape['tax_rate'])][key])


headers = ["tax_rate", " standard deviation", " average", " median", " maximum", " minimum", " range", " total_wealth", " gini", " bottom_quartile"]

avg_file = open('tax_data_avg.csv', 'w')
avg_file.write(",".join(headers) + "\n")


writer = csv.DictWriter(avg_file, headers)

for key, tax_rate in tax_data.iteritems():
    print tax_rate
    writer.writerow(tax_rate)
    

